﻿using MES.Desktop.BasicDataModule.Models;
using MES.Desktop.Common;
using MES.Desktop.Entities;
using MES.Desktop.IService;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MES.Desktop.BasicDataModule.ViewModels.Dialogs
{
    public class ModifyMaterialClassViewModel : DialogViewModelBase
    {
        public MaterialClassModel MCModel { get; set; } =
            new MaterialClassModel();

        public List<Entities.MaterialClassEntity> ParentNodes { get; set; } =
                new List<Entities.MaterialClassEntity>();

        public MaterialClassEntity CurrentParentNode { get; set; }

        IMaterialService _materialService;
        public ModifyMaterialClassViewModel(IMaterialService materialService)
        {
            _materialService = materialService;
        }
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            var model = parameters.GetValue<MaterialClassModel>("model");
            ParentNodes = parameters.GetValue<List<Entities.MaterialClassEntity>>("parents");
            ParentNodes.Insert(0, new Entities.MaterialClassEntity { ItemTypeName = "ROOT", ItemTypeId = 0 });


            if (model == null)
            {
                Title = "新增物料分类项";

                CurrentParentNode = ParentNodes[0];
            }
            else
            {
                Title = "编辑物料分类项";

                MCModel.ItemTypeId = model.ItemTypeId;
                MCModel.ItemTypeCode = model.ItemTypeCode;
                MCModel.ItemTypeName = model.ItemTypeName;
                MCModel.ParentTypeId = model.ParentTypeId;
                MCModel.Ancestors = model.Ancestors;
                MCModel.ItemOrProduct = model.ItemOrProduct;
                MCModel.EnableFlag = model.EnableFlag;
                MCModel.Remark = model.Remark;

                CurrentParentNode = ParentNodes.FirstOrDefault(p => p.ItemTypeId == model.ParentTypeId);
            }
        }

        public override void DoSave()
        {
            try
            {
                Entities.MaterialClassEntity materialClass = new Entities.MaterialClassEntity
                {
                    ItemTypeId = MCModel.ItemTypeId,
                    ItemTypeCode = MCModel.ItemTypeCode,
                    ItemTypeName = MCModel.ItemTypeName,
                    ParentTypeId = CurrentParentNode.ItemTypeId,
                    Ancestors = CurrentParentNode.ItemTypeName,
                    ItemOrProduct = MCModel.ItemOrProduct,
                    EnableFlag = MCModel.EnableFlag,
                    Remark = MCModel.Remark,
                };

                _materialService.UpdateClass(materialClass);

                base.DoSave();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
